package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
    //依赖注入service层
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    HttpSession session;

    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee) {
        //调用业务层返回结果
        R<Employee> loginEmployee = employeeService.login(employee);
        //判断是否验证成功
        if (loginEmployee.getCode() == 1) {
            session.setAttribute("employee", loginEmployee.getData().getId());
        }
        //返回结果
        return loginEmployee;
    }

    //退出
    @RequestMapping("/logout")
    public R<String> logout() {
        session.invalidate();
        return R.success("退出成功");
    }

    //添加用户信息
    @PostMapping
    public R<String> save(@RequestBody Employee employee) {
        //获取登录session中的id
        Long id = (Long) session.getAttribute("employee");
        //添加创建人和修改人的信息,完善数据
        employee.setCreateUser(id);
        employee.setUpdateUser(id);
        //调用业务层添加方法
        employeeService.save(employee);
        //返回结果
        return R.success("添加成功");
    }

    //分页查询
    @RequestMapping("/page")
    public R<Page<Employee>> findByPage(Integer page, Integer pageSize, String name) {
        //调用业务的分页查询方法
        Page<Employee> byPage = employeeService.findByPage(page, pageSize, name);
        return R.success(byPage);
    }

    //修改员工信息
    //前端传回的是json数据,需要@RequestBody
    @PutMapping
    public R<String> update(@RequestBody Employee employee) {
        //修改信息时将修改人的信息写入数据库
        Long id = (Long) session.getAttribute("employee");
        employee.setUpdateUser(id);
        //调用业务方法
        employeeService.update(employee);
        return R.success("修改成功");
    }

    //根据id查询用户信息
    @GetMapping("/{id}")
    public R<Employee> SelectById(@PathVariable Long id) {
        return employeeService.selectById(id);
    }
}
